package com.yohann.eduservice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.databind.util.BeanUtil;
import com.yohann.eduservice.entity.EduChapter;
import com.yohann.eduservice.entity.EduVideo;
import com.yohann.eduservice.entity.vo.ChapterVo;
import com.yohann.eduservice.entity.vo.VideoVo;
import com.yohann.eduservice.mapper.EduChapterMapper;
import com.yohann.eduservice.service.EduChapterService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yohann.eduservice.service.EduVideoService;
import com.yohann.servicebase.exception.GuliException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程 服务实现类
 * </p>
 *
 * @author Yohann
 * @since 2020-08-08
 */
@Service
public class EduChapterServiceImpl extends ServiceImpl<EduChapterMapper, EduChapter> implements EduChapterService {
    @Autowired
    private EduVideoService videoService;

    /**
     * 通过课程id获取章节信息
     * @param courseId
     * @return
     */
    @Override
    public List<ChapterVo> getChapterVideoById(String courseId) {
        //获取章节信息
        QueryWrapper<EduChapter> chapterQueryWrapper = new QueryWrapper<>();
        chapterQueryWrapper.eq("course_id", courseId);
        List<EduChapter> eduChapters = this.list(chapterQueryWrapper);

        //获取小节信息
        QueryWrapper<EduVideo> videoQueryWrapper = new QueryWrapper<>();
        videoQueryWrapper.eq("course_id", courseId);
        List<EduVideo> eduVideos = videoService.list(videoQueryWrapper);

        List<ChapterVo> finalList = new ArrayList<>();

        //填充章节vo数据
        for (EduChapter chapter : eduChapters) {
            //创建章节vo对象
            ChapterVo chapterVo = new ChapterVo();
            BeanUtils.copyProperties(chapter,chapterVo);

            //填充课时vo数据
            List<VideoVo> videoVoList = new ArrayList<>();

            for (EduVideo video : eduVideos) {
                if (chapter.getId().equals(video.getChapterId())){
                    //创建课时vo对象
                    VideoVo videoVo = new VideoVo();
                    BeanUtils.copyProperties(video,videoVo);

                    videoVoList.add(videoVo);
                }
            }

            chapterVo.setVideoVos(videoVoList);
            finalList.add(chapterVo);
        }

        return finalList;
    }

    /**
     * 通过章节id删除
     * @param id
     * @return
     */
    @Override
    public Boolean deleteChapter(String id) {
        //根据章节ID查小节表
        QueryWrapper<EduVideo> wrapper = new QueryWrapper<>();
        wrapper.eq("chapter_id",id);
        int count = videoService.count(wrapper);
        if (count > 0){
            throw new GuliException(20001,"有小节内容，不能删除章节");
        }else {
            return this.removeById(id);
        }
    }
}
